/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 3/15/13
 * Time: 8:26 AM
 * To change this template use File | Settings | File Templates.
 */
package societyGames.document.utility
{
import flash.utils.getQualifiedClassName;
import flash.filesystem.File;
import flash.net.SharedObject;

import mx.collections.ArrayCollection;

public class RecentlyOpened
{
  private var _sharedObject:SharedObject;
  private var _files:ArrayCollection = new ArrayCollection(); //File
  private var _maximumCount:int;

  public function RecentlyOpened(maximumCount:int)
  {
    _maximumCount = maximumCount;
    var name:String = getQualifiedClassName(this).replace("::", ".");
    _sharedObject = SharedObject.getLocal(name);
    load();
  }

  private function getPropertyNameFromIndex(index:int):String
  {
    return "_" + index.toString();
  }

  private function save():void
  {
    for (var index:int = 0; index < _maximumCount; index++)
    {
      _sharedObject.data[getPropertyNameFromIndex(index)] = _files[index].nativePath;
    }
    _sharedObject.flush();
  }

  private function load():void
  {
    for (var index:int = 0; index < _maximumCount; index++)
    {
      var key:String = getPropertyNameFromIndex(index);
      if (_sharedObject.data.hasOwnProperty(key))
      {
        var fileName:String = _sharedObject.data[key];
        _files.addItem(new File(fileName));
      }
      else
      {
        break;
      }
    }
  }

  /**
   * Add a new recent file.
   * @param file The file.
   */
  public function addRecent(file:File):void
  {
    //Remove any old copies of the file.
    removeRecent(file);
    //Add the file to the front, 0 position.
    _files.addItemAt(file, 0);
    if (_files.length > _maximumCount)
    {
      _files.removeItemAt(_maximumCount);
    }
    save();
  }

  public function removeRecent(file:File):void
  {
    for (var index:int = _files.length - 1; index >= 0; index--)
    {
      if (_files[index].nativePath == file.nativePath)
      {
        _files.removeItemAt(index);
      }
    }
  }

  /**
   * The recent file list. Element 0 is the most recent.
   */
  public function get files():ArrayCollection
  {
    return _files;
  }
}
}
